package toy.keli.picmap.tools;

import android.content.Intent;
import android.graphics.Point;
import android.net.Uri;
import android.os.StrictMode;
import android.widget.SeekBar;

import com.baidu.mapapi.model.LatLng;
import com.baidu.mapsdkexample.geometry.markercluster.MyItem;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import toy.keli.picmap.model.def;
import toy.keli.picmap.model.log;
import toy.keli.picmap.model.path;
import toy.keli.picmap.model.pic;
import toy.keli.picmap.model.system;
import toy.keli.picmap.model.time;
import toy.keli.picmap.util.utilZip;

public class Share extends Tools{
    String rootDir="/mnt/sdcard/picmap/";
    public Share(){
        File f = new File(rootDir+".nomedia");
        File fDir=f.getParentFile();
        if(!fDir.exists()) {
            fDir.mkdirs();
        }
        if(!f.exists()){
            system.file.put(f.getAbsolutePath(),new time().format());
        }
    }
    //压缩包分享  https://www.jb51.net/article/213219.htm
    public void packageShare(List<MyItem> mItemsFilter, boolean rarDo) {
        if(mItemsFilter.size()>500) {
            act.msg("分享的数量太多了，亲");
            return ;
        }
        if(!getPermission("android.permission.READ_PROFILE",()->{packageShare(mItemsFilter,rarDo); })) return;
//        Show.getTimeAnimation().setTaRuning(false);
        String uname=system.phoneName();
        String zipFile=rootDir+ uname+".pmr";
        String[] files = new String[mItemsFilter.size()+1];
        def jsons=new def();
        File fDir = new File(rootDir+"tmp/");
        File[] dir = fDir.listFiles();
        if(dir!=null && dir.length>0) {
            for (File file : dir) {
                file.delete();
            }
        }
        // fDir.delete();
        fDir.mkdirs();
        Point wsize = system.getScreenSize(act);
        StatusBar titleView = act.getStatusbar();
        system.fork(()->{
            int i=0;
            for(MyItem it:mItemsFilter){
                pic p=it.getPic();
                String fPath=rarDo ? it.getThumbnail(wsize.x,0): p.file;
                files[i++]=fPath;
                def d = it.getData();
                String filename=fPath.substring(fPath.lastIndexOf('/')+1);
                titleView.setText(""+i+"."+filename);
                d.set("file",filename);
                d.unset("id"); d.unset("uptime");
                jsons.push(d);
            }
            def info=new def();
            info.set("files",jsons);
            info.set("user",uname);
            String jsonFile=fDir.getAbsolutePath()+File.separator+"data.json";
            system.file.put(jsonFile,info.toJsonString());

            files[i]=jsonFile;
            Progress bar = act.getProgressBar();  SeekBar barObj = bar.getmProgresBar();
            int oldCount=barObj.getMax(), oldIndex=barObj.getProgress(); String oldText=bar.getmProgresText().getText().toString();
            titleView.setText("分享文件打包");
            bar.progresUpdate(0,files.length,"");
            utilZip.compress(zipFile,files,(index)->{
                act.getProgressBar().progresUpdate(index,0,"");
            });
            bar.progresUpdate(oldIndex,oldCount,oldText);
            titleView.setText("分享文件");
            Uri uri = Uri.fromFile(new File(zipFile));

            StrictMode.VmPolicy.Builder builder = new StrictMode.VmPolicy.Builder();
            StrictMode.setVmPolicy(builder.build());
            builder.detectFileUriExposure();

            Intent intent = new Intent();
            intent.setPackage("com.tencent.mm");
            intent.setAction(Intent.ACTION_SEND);
            intent.setType("*/*");
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            intent.putExtra(Intent.EXTRA_STREAM, uri);
            act.startActivity(Intent.createChooser(intent, "分享文件"));
        });
    }

    public void packageOpenafter(String to){
        String infoString=system.file.get(to+"/data.json");
        def info=new def.json(infoString);
        List<MyItem> items = new ArrayList<MyItem>();
        path pathModel = new path(to);
        int add=0;
        for(def fInfo : info.get("files")){
            String fPath=to+fInfo.get("file");
            pic pimg = new pic(fPath);
            fInfo.set("file",fPath);
            fInfo.set("pid",pathModel.id);
            if(pimg.id==0){
                pimg.setAttributs(fInfo);
//                boolean ok = pimg.save();
//                if(ok) add++;
            }
            fInfo.set("id",pimg.id);
            MyItem it = new MyItem(new LatLng(pimg.y,pimg.x), fInfo);
            items.add(it);
        }
        if(add>0){
            pathModel.add(add);
            msg("新增了"+add+"张图片");
        }
        act.registerOnLoadOver(()->{
            act.mClusterManager.addItems(items);
            act.refresh();
            Control.date[2]=-1;
            String title=to.replaceFirst(".+/(.+)/","$1");
            act.getStatusbar().setText(title+"行程分享");
            new Show.timeAnimation(items, Control.taNextTime);
        });
    }
    public void packageOpen(String file) {
        log.debug("package open:"+file);
        String name=file.substring(file.lastIndexOf('/')+1,file.lastIndexOf("."));
        name=name.replaceAll("\\d+_","");
        //Environment.getExternalStorageDirectory().getAbsolutePath()  + File.separator
        String to=rootDir+name+"/";
        String md5File=to+"last.md5";
        File dir=new File(to);
        act.setCanAddMarker(false);
        String lastMd5=system.file.get(md5File);
        String fileMd5=system.file.md5(file);
        //不要重复解压缩
        if(dir.exists() && lastMd5!=null && lastMd5.equals(fileMd5)) {
            time.Out(100,()->{packageOpenafter(to); });
        }else
        utilZip.unCompress(file,to,()->{
            packageOpenafter(to);
            system.file.put(md5File,fileMd5);
        });
    }
}
